<script lang="ts">
	import { page } from '$app/state';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import moment from 'moment';

	interface Props {
		onClose: () => void;
	}

	const props: Props = $props();

	let inviteCode = $state('');
	let expireDay = $state(7);

	const inviteUrl = $derived(
		`${page.url.protocol}//${page.url.host}/user/join?code=${inviteCode}`
	);

	async function genInviteCode() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.roadmapMemberApiClient.genInvite({
				sessionId: userStore.userSession,
				roadmapId: page.url.searchParams.get('roadmapId') ?? '',
				expireTime: BigInt(moment().add(expireDay, 'days').valueOf())
			}).response
		);
		inviteCode = res.inviteCode;
	}
</script>

<dialog class="modal modal-open">
	<div class="modal-box w-[500px] max-w-none">
		<button
			class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
			onclick={() => props.onClose()}>✕</button
		>
		<h3 class="text-lg font-bold">分享路线图</h3>
		{#if inviteCode == ''}
			<div class="max-h-[60vh] overflow-y-auto pr-[10px] flex-col space-y-4 pt-[20px]">
				<label class="label w-full">
					<span class="label w-[80px] text-right inline-block pr-[10px]">过期时间:</span>
					<select class="select w-full" bind:value={expireDay}>
						<option value={1}>1天</option>
						<option value={3}>3天</option>
						<option value={7}>一周</option>
						<option value={14}>两周</option>
						<option value={30}>一月</option>
					</select>
				</label>
			</div>
		{:else}
			<div class="flex gap-2 items-center">
				<div class="w-[400px] text-wrap break-all">
					{inviteUrl}
				</div>
				<button
					class="btn btn-primary"
					onclick={() =>
						navigator.clipboard.writeText(inviteUrl).then(() =>
							appStore.addToastMessage({
								level: 'info',
								content: '复制成功',
								keepTime: 2000
							})
						)}>复制</button
				>
			</div>
		{/if}

		{#if inviteCode == ''}
			<div class="modal-action">
				<button class="btn" onclick={() => props.onClose()}>取消</button>
				<button class="btn btn-primary" onclick={() => genInviteCode()}>生成</button>
			</div>
		{/if}
	</div>
</dialog>
